package com.kexun.controller;

import com.kexun.common.annotation.LoginManage;
import com.kexun.common.utils.GenerateUUID;
import com.kexun.common.utils.Result;
import com.kexun.config.shiro.IncorrectCaptchaException;
import com.kexun.entity.DO.Manage;
import com.kexun.entity.DO.Permission;
import com.kexun.entity.VO.Menu;
import com.kexun.service.ManageService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private ManageService manageService;
    @Value("${server.port}")
    private int port;


    @GetMapping("updPassword")
    public String updPassword(HttpSession session, HttpServletResponse response) {
        String generate = GenerateUUID.generate();
        session.setAttribute("pwd-token", generate);
        response.addCookie(new Cookie("pwd-token", generate));
        return "updatePassword";
    }

    @ResponseBody
    @PostMapping("updPassword")
    public Result updPassword(HttpServletRequest request, String oldPassword, String newPassword, @LoginManage Manage manage) {
        HttpSession session = request.getSession();
        String token = (String) session.getAttribute("pwd-token");
        String reqToken = getToken(request, "pwd-token");
        if (!token.equals(reqToken)) {
            return Result.error("token无效");
        }
        session.removeAttribute("pwd-token");
        manageService.updatePassword(oldPassword, newPassword, manage);
        return Result.success();
    }

    public String getToken(HttpServletRequest request, String tokenName) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (name.equals(tokenName)) {
                return cookie.getValue();
            }
        }
        return null;
    }


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(HttpServletRequest request, HttpServletResponse response) {
        Object exception = request.getAttribute("shiroLoginFailure");
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.isInstance(exception)) {
                msg = "账号不存在";
            } else if (IncorrectCredentialsException.class.isInstance(exception)) {
                msg = "密码不正确";
            } else if (IncorrectCaptchaException.class.isInstance(exception)) {
                msg = "验证码不正确";
            } else if (DisabledAccountException.class.isInstance(exception)) {
                msg = "用户已被禁用";
            } else {
                msg = "未知错误" + exception.toString();
            }
            return Result.error(msg);
        }
        return Result.success();
    }


    @RequestMapping(method = RequestMethod.GET, value = "/logout")
    public String loginOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login";
    }


    //主页
    @GetMapping({"index", "/"})
    public String index(Model model, @LoginManage Manage manage) {
        List<Permission> permissionList = manage.getRole().getPermissionList();
        List<Menu> menu = createMenu(permissionList, 0);
        model.addAttribute("munu", menu);
        model.addAttribute("nickName", manage.getNickName());
        model.addAttribute("manageName", manage.getManageName());
        model.addAttribute("port", port);
        return "index";
    }

    @ResponseBody
    @GetMapping({"/menu"})
    public Result index(@LoginManage Manage manage) {
        List<Permission> permissionList = manage.getRole().getPermissionList();
        List<Menu> menu = createMenu(permissionList, 0);
        return Result.success("成功", menu);
    }


    private List<Menu> createMenu(List<Permission> permissionList, int pid) {
        List<Menu> list = new ArrayList<Menu>();
        for (Permission permission : permissionList) {
            if (permission.getIsButton() == 0) {
                if (permission.getParentId() == pid) {
                    Menu menu = new Menu();
                    menu.setId(permission.getId());
                    menu.setUrl(permission.getPermissionName());
                    menu.setMenuName(permission.getMenuName());
                    menu.setIcon(permission.getMenuIcon());
                    if (permission.getCount() > 0) {
                        menu.setChildren(createMenu(permissionList, permission.getId()));
                    }
                    list.add(menu);
                }
            }
        }
        return list;
    }


}
